const Koa = require('koa')//引入koa
const app = new Koa()//当前请求的实例
const views = require('koa-views')
const json = require('koa-json')//json处理
const onerror = require('koa-onerror')//错误处理
const bodyparser = require('koa-bodyparser')//post上传数据处理
const logger = require('koa-logger')//日志
const session=require('koa-generic-session')
const redisStore=require('koa-redis')
const path=require('path')
const fs=require('fs')
const morgan=require('koa-morgan')//用koa-morgan写入日志,用法和morgan基本一样

//引入路由文件
const index = require('./routes/index')
const users = require('./routes/users')
const blog = require('./routes/blog')
const user = require('./routes/user')

const {REDIS_CONF}=require('./conf/db')

// error handler错误监测
onerror(app)

// middlewares处理post上传数据
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())//日志
app.use(require('koa-static')(__dirname + '/public'))//对应public文件夹

//对应views文件夹
app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger 计算当前服务请求的耗时
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

const ENV=process.env.NODE_ENV;
if(ENV!=='production'){
  //开发环境 || 测试环境
  app.use(morgan('dev'));
}else{
  //线上环境
  const logFileName=path.join(__dirname,'logs','access.log');
  const writeStream=fs.createWriteStream(logFileName,{
    flags:'a',//文件追加
  });
  app.use(morgan('combined',{
    stream:writeStream,//流：传入指定文件,默认为process.stdout(打印在控制台)
  }));
}

//session配置
app.keys=['WJiol#23123_']
app.use(session({
  //配置cookie
  cookie:{
    path:'/',
    httpOnly:true,
    maxAge:24*60*60*1000
  },
  //配置redis
  store:redisStore({
    // all:'127.0.0.1:6379'  //写死本地的redis
    all:`${REDIS_CONF.host}:${REDIS_CONF.port}`
  })
}))

// routes 路由处理
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(blog.routes(), blog.allowedMethods())
app.use(user.routes(), user.allowedMethods())

// error-handling 错误处理
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
